'use strict';

const express = require('express');
const dbutility = require('../../common/dbutility');
const gputility = require('../../common/gputility');
const utility = require('../../common/utility');
const logger = require('../../common/logutility').logger('chgPwdInp');
let router = express.Router();

router.get('/', function(req, res) {
    gputility.excuteGP(getGP(req, res));
});

router.post('/', function(req, res) {
    gputility.excuteGP(postGP(req, res));
});

function* getGP(req, res) {
    try {
        res.render('./cou/chgPwdInp');
    } catch (e) {
        logger.error(e);
        res.redirect('/error');
    }
}

function* postGP(req, res) {
    try {
        if (req.body.couPwdNew1 !== req.body.couPwdNew2) {
            return res.render('./cou/chgPwdInp', { errorInfo: '新密码不一致，请重新操作！' })
        }

        let encryptedCouPwdOld = utility.encrypt(req.body.couPwdOld);
        let encryptedCouPwdNew = utility.encrypt(req.body.couPwdNew1);
        let couTel = req.session.userTel;
        let cou = yield dbutility.couModel.getUserAuth(couTel, encryptedCouPwdOld);
        if (cou) {
            yield dbutility.couModel.updateCouPwd(couTel, encryptedCouPwdNew);
            res.redirect('/chgPwdCmp');
        } else {
            res.render('./cou/chgPwdInp', { errorInfo: '旧密码输入错误，请重新操作！' })
        }

        logger.info('Chg Pwd Cou Info:');
        logger.info(cou);
    } catch (e) {
        logger.error(e);
        res.redirect('/error');
    }
}

module.exports = router;